"""
简化版MySQL连接示例
基于原有的xiyan.py，修改为连接远程MySQL数据库
"""
from sqlalchemy import create_engine
from src.schema_engine import SchemaEngine
from config.mysql_config import MYSQL_CONFIG

def create_mysql_engine():
    """创建MySQL数据库引擎"""
    # 构建MySQL连接字符串
    connection_string = f"mysql+pymysql://{MYSQL_CONFIG['user']}:{MYSQL_CONFIG['password']}@{MYSQL_CONFIG['host']}:{MYSQL_CONFIG['port']}/{MYSQL_CONFIG['database']}?charset={MYSQL_CONFIG['charset']}"
    
    try:
        engine = create_engine(connection_string)
        print(f"✅ 成功连接到MySQL数据库: {MYSQL_CONFIG['host']}:{MYSQL_CONFIG['port']}/{MYSQL_CONFIG['database']}")
        return engine
    except Exception as e:
        print(f"❌ MySQL数据库连接失败: {e}")
        return None

def mschema_mysql():
    """
    使用MySQL数据库生成Schema信息
    类似于原有的xiyan.py中的mschema()函数
    """
    # 创建MySQL数据库引擎
    db_engine = create_mysql_engine()
    if not db_engine:
        return None
    
    try:
        # 使用SchemaEngine分析MySQL数据库结构
        schema_engine = SchemaEngine(engine=db_engine, db_name=MYSQL_CONFIG['database'])
        mschema = schema_engine.mschema
        mschema_str = mschema.to_mschema()
        print(mschema_str)
        return mschema_str
    except Exception as e:
        print(f"❌ 生成Schema失败: {e}")
        return None

if __name__ == '__main__':
    print("🚀 启动MySQL Schema分析工具...")
    print("📋 请确保已在mysql_config.py中配置正确的数据库连接信息")
    print("-" * 50)
    
    # 显示当前配置信息（隐藏密码）
    print(f"📊 数据库配置:")
    print(f"   主机: {MYSQL_CONFIG['host']}")
    print(f"   端口: {MYSQL_CONFIG['port']}")
    print(f"   用户: {MYSQL_CONFIG['user']}")
    print(f"   数据库: {MYSQL_CONFIG['database']}")
    print("-" * 50)
    
    # 生成Schema
    result = mschema_mysql()
    
    if result:
        print("\n✅ Schema分析完成!")
    else:
        print("\n❌ Schema分析失败，请检查数据库连接配置")